import { getToken, setToken, removeToken, setLoginTime, getLoginTime } from '@/utils/auth'
import { login, getUserInfo, getUserRoles } from '@/api/user.js'

const state = {
  // 状态
  // 设置token为共享状态，初始化的时候在缓存读取
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
    // 保存登入时间
    setLoginTime()
  },
  // 删除token
  removeToken(state, token) {
    state.token = null
    removeToken()
  },
  // 保存用户信息
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  // 删除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  async login(context, data) {
    const result = await login(data)
    if (result) {
      context.commit('setToken', result.jwt)
    }
  },
  // 获取用户资料action
  async getUserInfo(context) {
    const baseInfo = await getUserInfo()
    const rolesInfo = await getUserRoles()
    console.log('检测页面是否存获取新数据', { ...baseInfo, ...rolesInfo })
    context.commit('setUserInfo', { ...baseInfo, ...rolesInfo })
  },
  // 登出判断
  logout(context) {
    // 清空token
    context.commit('removeToken')
    // 清除用户信息
    context.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
